package net.huashitong.taskjob.web;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.security.SysPrincipal;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Indicators.entity.TertiaryIndustry;
import net.huashitong.Indicators.service.TertiaryIndustryService;
import net.huashitong.question.entity.SupervisionLog;
import net.huashitong.question.entity.TaskRecord;
import net.huashitong.question.filter.TaskLogFilter;
import net.huashitong.question.filter.TaskRecordFilter;
import net.huashitong.question.service.SupervisionLogService;
import net.huashitong.question.service.TaskRecordService;
import net.huashitong.taskjob.databean.GraphBean;
import net.huashitong.taskjob.entity.MessageList;
import net.huashitong.taskjob.entity.TaskJob;
import net.huashitong.taskjob.entity.TaskMethod;
import net.huashitong.taskjob.filter.MessageListFilter;
import net.huashitong.taskjob.filter.TaskJobFilter;
import net.huashitong.taskjob.service.*;
import net.huashitong.taskjob.util.UtilsTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*;

@Controller
@RequestMapping("/jobmanages")
public class TaskJobCtrl extends JsonBaseController {

    @Autowired
    private TaskJobService taskJobService;
    @Autowired
    private SupervisionLogService supervisionLogService;
    @Autowired
    private TaskRecordService taskRecordService;
    @Autowired
    private SupervisionService supervisionService;
    @Autowired
    private ResDpteService resDpteService;
    @Autowired
    private TertiaryIndustryService tertiaryIndustryService;
    @Autowired
    private TaskMethodService methodService;
    @Autowired
    private MessageListService messageListService;


    @Override
    protected String getView(String s) {
        return "/modules/sys/jobmanage/" + s;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String initPage() {
        return getView("query");
    }

    /**
     * 初始化数据
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid query(@ModelAttribute TaskJobFilter filter) {
        List<TaskJob> list = taskJobService.getTaskLists(filter);
        return coverJqGrid(filter, list);
    }

    /**
     * 查询参数
     *
     * @return
     */
    @RequestMapping("/filter")
    public String filter() {
        return getView("filter");
    }

    /**
     * 打开手动新建任务
     *
     * @param model
     * @return url
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String showAddView(@ModelAttribute TaskJobFilter filter, Model model) {
        //查询所有督查组
        List<SysDept> supervisionList = supervisionService.queryAllSupervisions();
        //查询所有责任单位
        List<SysDept> resDepts = resDpteService.queryAllResDepts();
        //查询所有主要经济社会发展指标
        List<TertiaryIndustry> industries = tertiaryIndustryService.queryByIndicatorLevel("主要经济社会发展");
        model.addAttribute("industries", industries);
        model.addAttribute("supervisionList", supervisionList);
        model.addAttribute("resDepts", resDepts);
        model.addAttribute("taskjob", filter);
        return getView("createTaskForm");
    }

    /**
     * 保存手动新建任务提交
     */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Message create(@ModelAttribute TaskJobFilter filter) {
        taskJobService.saveTaskJob(filter);
        return coverMessage("200");
    }

    /**
     * 修改查看任务详情
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String showEdit(Model model, @PathVariable String id) {
        //查询所有督查组
        List<SysDept> supervisionList = supervisionService.queryAllSupervisions();
        //查询所有责任单位
        List<SysDept> resDepts = resDpteService.queryAllResDepts();
        model.addAttribute("supervisionList", supervisionList);
        model.addAttribute("resDepts", resDepts);
        TaskJob task = taskJobService.getById(id);
        model.addAttribute("taskJob", task);
        return getView("editForm");
    }

    /**
     * 修改任务
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Message editTaskJob(@ModelAttribute TaskJobFilter filter) {
        TaskJob task = taskJobService.getById(filter.getSysId());
        if (ObjectUtils.isBlank(task)) {
            return coverMessage("500", "找不到该任务，请刷新页面");
        }
        taskJobService.updateTaskJob(filter, task);
        return coverMessage("200", "任务修改成功");
    }


    /**
     * 节点图流程
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping("/getTaskNodes")
    public Message getTaskNodes(@RequestBody TaskJobFilter filter) {

        logger.info("流程开始时间 -----" + UtilsTools.getCurrentDateTime() + "---------------");
        //流程图阶段拼接
        String[] allNodes = {"任务生成", "任务开始", "任务执行中", "任务完成", "任务未完成", "反馈攻坚", "完成情况", "督查记录", "督查组需协调事项", "责任单位需协调事项", "督查得分"};
        List<GraphBean> lists = new ArrayList<>();
        GraphBean bean = new GraphBean();
        bean.setSource("任务生成");
        bean.setTarget("任务开始");
        lists.add(bean);
        bean = new GraphBean();
        bean.setSource("任务开始");
        bean.setTarget("任务执行中");
        lists.add(bean);
        TaskJob task = taskJobService.getById(filter.getSysId());
        //判断是否有督查记录
        List<SupervisionLog> logs = supervisionLogService.getMissionLog(task.getSysId());
        if (ObjectUtils.isNotBlank(logs)) {
            bean = new GraphBean();
            bean.setSource("任务执行中");
            bean.setTarget("督查记录");
            lists.add(bean);
        }
        //是否有完成情况
        List<TaskRecord> records = taskRecordService.getRecordsById(task.getSysId());
        if (ObjectUtils.isNotBlank(records)) {
            bean = new GraphBean();
            bean.setSource("任务执行中");
            bean.setTarget("完成情况");
            lists.add(bean);
        }
        if ("1".equals(task.getTaskResult())) //任务是否完成 1 完成
        {
            bean = new GraphBean();
            bean.setSource("任务执行中");
            bean.setTarget("任务完成");
            lists.add(bean);
            bean = new GraphBean();
            bean.setSource("任务完成");
            bean.setTarget("督查得分");
            lists.add(bean);
        } else {  // 未完成
            Date planEnd = null;
            Date enddate = null;
            try {
                planEnd = UtilsTools.StringToDate(task.getPlanEndDate());
                enddate = UtilsTools.StringToDate(UtilsTools.getCurrentDate());
                if (planEnd.compareTo(enddate) < 0)   //15天后 是否完成
                {
                    bean = new GraphBean();
                    bean.setSource("任务执行中");
                    bean.setTarget("任务未完成");
                    lists.add(bean);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if ("1".equals(task.getIsFeedback())) //未完成是否反馈给攻坚办
            {
                bean = new GraphBean();
                bean.setSource("任务未完成");
                bean.setTarget("反馈攻坚");
                lists.add(bean);
                if ("1".equals(task.getTaskResult()))//再次判断任务是否完成
                {
                    bean = new GraphBean();
                    bean.setSource("反馈攻坚");
                    bean.setTarget("督查得分");
                    lists.add(bean);
                  /*  bean  = new GraphBean();
                    bean.setSource("任务完成");
                    bean.setTarget("督查得分");
                    lists.add(bean);*/
                } else {
                    //判断是否再次生成任务
                    bean = new GraphBean();
                    bean.setSource("反馈攻坚");
                    bean.setTarget("任务生成");
                    lists.add(bean);
                }
            }
          /*  bean  = new GraphBean();
            bean.setSource("任务完成");
            bean.setTarget("督查得分");
            lists.add(bean);*/
        }
        Map<String, Object> map = new HashMap<>();
        map.put("graph", lists);
        int[] greenNode = {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
        for (GraphBean item : lists) {
            for (int i = 0; i < allNodes.length; i++) {
                if (item.getTarget().equals(allNodes[i])) {
                    greenNode[i] = 0;
                }
            }
        }
        map.put("green", greenNode);
        logger.info("结束时间 -----" + UtilsTools.getCurrentDateTime() + "---------------");
        return coverMessage("200", "successful", map);
    }

    /**
     * 打开任务催办按钮（我要催办）
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/createTaskLog/{id}", method = RequestMethod.GET)
    public String showTaskLogView(@PathVariable String id, HttpServletRequest request, Model model) {

        //获取用户*
        SysPrincipal bnpUser = SysUserUtils.getSysPrincipal();
        //督查任务
        TaskJob task = taskJobService.getById(id);
        List<TaskMethod> methods = methodService.getAllMethon();
        List<TaskRecord> lists = taskRecordService.getRecordsById(id);
        List<SupervisionLog> supervisionLogs = supervisionLogService.getMissionLog(id);
        //填写时间格式去掉-
        for (SupervisionLog s : supervisionLogs) {
            s.setCreateDate(s.getCreateDate().replace("-", ""));
        }

        model.addAttribute("task", task);
        model.addAttribute("methods", methods);
        model.addAttribute("listRecords", lists);
        model.addAttribute("supervisionLogs", supervisionLogs);
        return getView("logForm");
    }

    /**
     * 添加催办记录。（督查组）
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/createTaskLog", method = RequestMethod.POST)
    public Message createTaskLog(@ModelAttribute TaskLogFilter filter) {
        filter.setTaskId(filter.getSysId());
        filter.setSysId(null);
        TaskJob task = taskJobService.getById(filter.getTaskId());
        filter.setTaskTimes(task.getTaskTimes());

        boolean isRight = supervisionLogService.saveCuiBanLog(filter);
        if (!isRight) {
            //无添加记录
            return coverMessage("201", "记录填写不规范", false);
        }
        taskJobService.update(task);

        //添加督查动态消息列表
        MessageList messageList = new MessageList();
        messageList.setIsRead("0");
        messageList.setTaskId(task.getSysId());
        messageList.setUserId(task.getUserId());
        messageListService.save(messageList);

        return coverMessage("200", "提交成功", true);
    }

    /**
     * 添加完成情况（责任单位）
     *
     * @param model
     * @return url
     */
    @RequestMapping(value = "/createRespRecord/{id}", method = RequestMethod.GET)
    public String showRespEdit(Model model, @PathVariable String id) {

        //督查任务
        TaskJob task = taskJobService.getById(id);
        List<TaskMethod> methods = methodService.getAllMethon();
        List<TaskRecord> lists = taskRecordService.getRecordsById(id);
        List<SupervisionLog> supervisionLogs = supervisionLogService.getMissionLog(id);
        //填写时间格式去掉-
        for (SupervisionLog s : supervisionLogs) {
            s.setCreateDate(s.getCreateDate().replace("-", ""));
        }

        model.addAttribute("task", task);
        model.addAttribute("methods", methods);
        model.addAttribute("listRecords", lists);
        model.addAttribute("supervisionLogs", supervisionLogs);
        return getView("addCompletion_form");
    }

    /**
     * 完成情况提交（责任单位）
     **/
    @ResponseBody
    @RequestMapping(value = "/createRespRecord", method = RequestMethod.POST)
    public Message createCompleteInfo(@ModelAttribute TaskRecordFilter filter) {

//        if (StringUtils.isBlank(filter.getTaxproof())) {
//            //没有上传佐证材料
//            return coverMessage("201", "提交失败，没有上传佐证材料", false);
//        }
        filter.setTaskId(filter.getSysId());
        filter.setSysId(null);
        TaskJob task = taskJobService.getById(filter.getTaskId());
        filter.setResDept(task.getResDept());
        boolean flag = taskRecordService.saveRocord(filter); //保存完成情况
        if (!flag) {
            //无添加记录
            return coverMessage("201", "记录填写不规范", false);
        }
        //添加督查动态消息列表
        MessageList messageList = new MessageList();
        messageList.setIsRead("0");
        messageList.setTaskId(task.getSysId());
        //获取督查组成员id
        List<SysUser> sysUsers = supervisionService.querySupervisionUserByDeptId(task.getGroupCode());
        messageList.setUserId(sysUsers.get(0).getSysId());
        messageListService.save(messageList);

        return coverMessage("200");
    }

    /**
     * 重新生成任务
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/rebuildjob/{id}", method = RequestMethod.GET)
    public String showreJob(Model model, @PathVariable String id) {
        //查询所有督查组
        List<SysDept> supervisionList = supervisionService.queryAllSupervisions();
        //查询所有责任单位
        List<SysDept> resDepts = resDpteService.queryAllResDepts();
        //查询所有主要经济社会发展指标
        List<TertiaryIndustry> industries = tertiaryIndustryService.queryByIndicatorLevel("主要经济社会发展");
        model.addAttribute("industries", industries);
        model.addAttribute("supervisionList", supervisionList);
        model.addAttribute("resDepts", resDepts);
        TaskJob task = taskJobService.getById(id);
        model.addAttribute("reStartTask", task);
        return getView("restartForm");
    }

    /**
     * 重新生成任务节点。
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/rebuildjob", method = RequestMethod.POST)
    public Message rebuildJob(@ModelAttribute TaskJobFilter filter) {

        TaskJob task = taskJobService.getById(filter.getSysId());
        if (ObjectUtils.isBlank(task)) {
            return coverMessage("500", "找不到该任务，请刷新页面");
        }

        taskJobService.saveTaskJob(filter);
        //设置重新督查
        task.setIsRebuild("1");
        //设置任务失效
        task.setAaa001("0");
        taskJobService.update(task);

        return coverMessage("200", "重新生成任务成功");
    }

    /**
     * 责任单位 deptId 动态修改
     * @param deptId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryResUserByDeptId", method = RequestMethod.GET)
    public SysUser queryResUserByDeptId(String deptId) {
        List<SysUser> list = resDpteService.queryResUserByDeptId(deptId);
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    /**
     * 督查组 deptId 动态修改
     * @param deptId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/querySupervisionUserByDeptId")
    public SysUser querySupervisionUserByDeptId(String deptId) {
        List<SysUser> list = supervisionService.querySupervisionUserByDeptId(deptId);
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

//    /**
//     * 督查详情
//     *
//     * @param model
//     * @return url
//     */
//    @RequestMapping(value = "/supervisionAskList/{id}", method = RequestMethod.GET)
//    public String showSupervisionAskList(Model model, HttpServletRequest request, @PathVariable String id) {
//        TaskJob task = taskJobService.getById(id);
//        model.addAttribute("task", task);
//        List<SupervisionLog> logs = supervisionLogService.getMissionLog(id);
//        model.addAttribute("logs", logs);
//        //业主单位或者审批部门查看督查详情，则督查动态改成已读
//        SysPrincipal bnpUser = SysUserUtils.getSysPrincipal();
//        List<SysUser> list = supervisionService.querySupervisionUserByDeptId(bnpUser.getDeptId());
//        String superFlag = list.get(0).getSuperFlag();
//        if ("0".equals(superFlag) && list.size()>0) {
//            MessageListFilter mf = new MessageListFilter();
//            mf.setIsRead("0");
//            mf.setUserId(list.get(0).getSysId());
//            mf.setTaskId(task.getSysId());
//            List<MessageList> msgList = messageListService.queryNoReadMessage(mf);
//            for (MessageList messageList : msgList) {
//                messageList.setIsRead("1");
//            }
//            messageListService.batchUpdate(msgList);
//        }
//        return getView("supervisionAskList");
//    }
//
//    /**
//     * 反馈详情
//     *
//     * @param model
//     * @return url
//     */
//    @RequestMapping(value = "/feedbackInfoList/{id}", method = RequestMethod.GET)
//    public String showfeedbackInfoList(Model model, HttpServletRequest request, @PathVariable String id) {
//        TaskJob task = taskJobService.getById(id);
////        model.addAttribute("datebean", task);
//        //被督查单位的<反馈记录>
//        List<TaskRecord> lists = taskRecordService.getRecordsById(id);
//        model.addAttribute("listRecords", lists);
//        //督查组查看反馈记录，则督查动态更改未读状态
//        SysPrincipal bnpUser = SysUserUtils.getSysPrincipal();
//        List<SysUser> list = supervisionService.querySupervisionUserByDeptId(bnpUser.getDeptId());
//        String superFlag = list.get(0).getSuperFlag();
//        if ("0".equals(superFlag) && list.size()>0)  {
//            MessageListFilter mf = new MessageListFilter();
//            mf.setIsRead("0");
//            mf.setUserId(list.get(0).getSysId());
//            mf.setTaskId(task.getSysId());
//            List<MessageList> msgList = messageListService.queryNoReadMessage(mf);
//            for (MessageList messageList : msgList) {
//                messageList.setIsRead("1");
//            }
//            messageListService.batchUpdate(msgList);
//        }
//
//        return getView("feedbackInfoList");
//    }

}
